package libtool65.cmd;

import java.util.HashMap;

public class CommandLineParser {
	private HashMap<String, Command> commands = new HashMap<String, Command>();
	
	public CommandLineParser()
	{
		commands.put("info", new InfoCommand());
		commands.put("link", new LinkCommand());
		commands.put("relink", new RelinkCommand());
	}

	public Command parse(String[] args) {
		if (args.length == 0)
		{
			printUsage();
			return null;
		}
		Command command = commands.get(args[0]);
		if (command == null)
		{
			System.out.println("Unknown command \""+args[0]+"\"");
			printUsage();
			return null;
		}
		if (args.length > 1 && args[1].equals("--help"))
		{
			command.printHelp();
			return null;
		}
		for (int i = 1; i < args.length; i++)
		{
			if (args[i].startsWith("--"))
			{
				Option option = command.addOption(args[i]);
				if (option == null)
					System.out.println("Unknown option "+args[i]);
				else
				{
					if (option.hasArgument() && i < args.length)
						option.setArgument(args[++i]);
				}
			}
			else
				command.addParameter(args[i]);
		}
		return command;
	}

	public void printUsage() {
		System.out.println("Usage: libtool65 <command> [parameters] [files]");
		System.out.println("Available commands are:");
		for (String command : commands.keySet())
			System.out.println("   "+command);
		System.out.println("Use \"libtool65 <command> --help\" to get help for a command.");
	}
}
